<template>
  <div class="huarongdao-game-container">
    <div class="game-header">
      <h1>华容道解谜</h1>
      <div class="game-info">
        <div class="info-item">
          <span>当前关卡:</span>
          <span class="info-value">{{ currentLevel + 1 }} / {{ levels.length }}</span>
        </div>
        <div class="info-item">
          <span>移动步数:</span>
          <span class="info-value">{{ moveCount }}</span>
        </div>
      </div>
    </div>
    
    <div class="game-area">
      <div 
        class="game-board" 
        :style="{ 
          width: `${boardSize[1] * GRID_SIZE}px`, 
          height: `${boardSize[0] * GRID_SIZE}px` 
        }"
        @mousedown="handleMouseDown"
        @mousemove="handleMouseMove"
        @mouseup="handleMouseUp"
        @mouseleave="handleMouseUp"
      >
        <!-- 绘制网格背景 -->
        <div class="grid-background">
          <div 
            v-for="(row, rowIndex) in boardSize[0]" 
            :key="`grid-row-${rowIndex}`"
            class="grid-row"
          >
            <div 
              v-for="(col, colIndex) in boardSize[1]" 
              :key="`grid-col-${rowIndex}-${colIndex}`"
              class="grid-cell"
            ></div>
          </div>
        </div>
        
        <!-- 绘制方块 -->
        <div class="blocks-container">
          <div 
            v-for="block in blocks" 
            :key="`block-${block.id}`"
            class="game-block"
            :class="{ 'dragging': draggedBlock && draggedBlock.id === block.id }"
            :style="{
              backgroundColor: getBlockColor(block.type),
              left: `${block.x * GRID_SIZE}px`,
              top: `${block.y * GRID_SIZE}px`,
              width: `${block.width * GRID_SIZE}px`,
              height: `${block.height * GRID_SIZE}px`,
              transform: draggedBlock && draggedBlock.id === block.id ? `translate(${dragOffset.x}px, ${dragOffset.y}px)` : 'none',
              zIndex: draggedBlock && draggedBlock.id === block.id ? 10 : 1
            }"
          >
            <span class="block-label">{{ block.type }}</span>
          </div>
        </div>
      </div>
    </div>
    
    <div class="game-controls">
      <select v-model="currentLevel" @change="loadLevel" class="level-select">
        <option v-for="(level, index) in levels" :key="level.id" :value="index">
          关卡 {{ index + 1 }}
        </option>
      </select>
      
      <button @click="resetLevel" class="control-button reset-button">
        重玩关卡
      </button>
      
      <button @click="showHelp = !showHelp" class="control-button help-button">
        {{ showHelp ? '隐藏' : '显示' }}帮助
      </button>
    </div>
    
    <div v-if="showHelp" class="game-help">
      <p>通过拖拽方块，帮助曹操从出口逃脱。</p>
      <p>• 曹操：红色2×2方块</p>
      <p>• 关羽、张飞、赵云、马超、黄忠：绿色或蓝色1×2或2×1方块</p>
      <p>• 士兵：灰色1×1方块</p>
    </div>
    
    <!-- 胜利弹窗 -->
    <div v-if="isVictory" class="victory-modal-overlay" @click.self="closeVictoryModal">
      <div class="victory-modal">
        <h2>恭喜过关！</h2>
        <p>关卡 {{ currentLevel + 1 }} 完成！</p>
        <p>移动步数：{{ moveCount }}</p>
        <div class="victory-buttons">
          <button @click="nextLevel" v-if="currentLevel < levels.length - 1" class="control-button next-level-button">
            下一关
          </button>
          <button @click="closeVictoryModal" class="control-button">
            确定
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue';
import { levels } from './HuarongdaoLevels.js';

// 游戏配置
const GRID_SIZE = 80; // 网格大小

// 游戏状态
const currentLevel = ref(0);
const moveCount = ref(0);
const board = ref([]);
const blocks = ref([]);
const boardSize = ref([4, 5]); // 默认棋盘大小 [rows, cols]
const exitPos = ref([3, 3]); // 默认出口位置
const isVictory = ref(false);
const showHelp = ref(false);

// 拖拽状态
const draggedBlock = ref(null);
const dragStartPos = ref({ x: 0, y: 0 });
const dragOffset = ref({ x: 0, y: 0 });
const isDragging = ref(false);

// 初始化游戏
onMounted(() => {
  loadLevel();
});

// 加载关卡
function loadLevel() {
  const levelData = levels[currentLevel.value];
  if (!levelData) return;
  
  // 重置游戏状态
  moveCount.value = 0;
  isVictory.value = false;
  draggedBlock.value = null;
  isDragging.value = false;
  
  // 设置棋盘大小和出口位置
  boardSize.value = levelData.boardSize;
  exitPos.value = levelData.exit;
  
  // 初始化棋盘
  board.value = Array.from({ length: boardSize.value[0] }, () => Array(boardSize.value[1]).fill(0));
  
  // 创建方块实例
  blocks.value = levelData.blocks.map(block => ({
    ...block
  }));
  
  // 更新棋盘数据
  updateBoard();
}

// 更新棋盘数据
function updateBoard() {
  // 清空棋盘
  for (let y = 0; y < boardSize.value[0]; y++) {
    for (let x = 0; x < boardSize.value[1]; x++) {
      board.value[y][x] = 0;
    }
  }
  
  // 标记方块位置
  blocks.value.forEach(block => {
    for (let y = 0; y < block.height; y++) {
      for (let x = 0; x < block.width; x++) {
        board.value[block.y + y][block.x + x] = block.id;
      }
    }
  });
}

// 获取方块颜色
function getBlockColor(type) {
  const colors = {
    '曹操': '#e74c3c',
    '关羽': '#2ecc71',
    '张飞': '#3498db',
    '赵云': '#9b59b6',
    '马超': '#f39c12',
    '黄忠': '#1abc9c',
    '士兵': '#95a5a6'
  };
  return colors[type] || '#34495e';
}

// 处理鼠标按下事件
function handleMouseDown(event) {
  const rect = event.currentTarget.getBoundingClientRect();
  const mouseX = event.clientX - rect.left;
  const mouseY = event.clientY - rect.top;
  
  // 查找被点击的方块
  const clickedBlock = blocks.value.find(block => {
    return mouseX >= block.x * GRID_SIZE && 
           mouseX < (block.x + block.width) * GRID_SIZE && 
           mouseY >= block.y * GRID_SIZE && 
           mouseY < (block.y + block.height) * GRID_SIZE;
  });
  
  if (clickedBlock) {
    draggedBlock.value = clickedBlock;
    dragStartPos.value = { x: mouseX, y: mouseY };
    dragOffset.value = { x: 0, y: 0 };
    isDragging.value = true;
    
    // 阻止默认行为
    event.preventDefault();
  }
}

// 处理鼠标移动事件
function handleMouseMove(event) {
  if (!isDragging.value || !draggedBlock.value) return;
  
  const rect = event.currentTarget.getBoundingClientRect();
  const mouseX = event.clientX - rect.left;
  const mouseY = event.clientY - rect.top;
  
  // 计算拖拽偏移量
  dragOffset.value = {
    x: mouseX - dragStartPos.value.x,
    y: mouseY - dragStartPos.value.y
  };
}

// 处理鼠标释放事件
function handleMouseUp(event) {
  if (!isDragging.value || !draggedBlock.value) return;
  
  isDragging.value = false;
  
  // 计算移动方向和距离
  const moveThreshold = GRID_SIZE / 2;
  
  if (Math.abs(dragOffset.value.x) > moveThreshold || Math.abs(dragOffset.value.y) > moveThreshold) {
    // 确定移动方向
    let direction = '';
    if (Math.abs(dragOffset.value.x) > Math.abs(dragOffset.value.y)) {
      direction = dragOffset.value.x > 0 ? 'right' : 'left';
    } else {
      direction = dragOffset.value.y > 0 ? 'down' : 'up';
    }
    
    // 尝试移动方块
    if (canMoveBlock(draggedBlock.value, direction)) {
      moveBlock(draggedBlock.value, direction);
      moveCount.value++;
      
      // 检查是否胜利
      if (checkVictory()) {
        isVictory.value = true;
      }
    }
  }
  
  // 重置拖拽状态
  dragOffset.value = { x: 0, y: 0 };
  draggedBlock.value = null;
}

// 检查方块是否可以移动
function canMoveBlock(block, direction) {
  let dx = 0, dy = 0;
  
  switch (direction) {
    case 'left': dx = -1; break;
    case 'right': dx = 1; break;
    case 'up': dy = -1; break;
    case 'down': dy = 1; break;
  }
  
  // 检查每个格子是否可以移动
  for (let y = 0; y < block.height; y++) {
    for (let x = 0; x < block.width; x++) {
      const newX = block.x + dx + x;
      const newY = block.y + dy + y;
      
      // 检查边界
      if (newX < 0 || newX >= boardSize.value[1] || newY < 0 || newY >= boardSize.value[0]) {
        return false;
      }
      
      // 检查是否有其他方块阻挡
      if (board.value[newY][newX] !== 0 && board.value[newY][newX] !== block.id) {
        return false;
      }
    }
  }
  
  return true;
}

// 移动方块
function moveBlock(block, direction) {
  // 从棋盘移除
  for (let y = 0; y < block.height; y++) {
    for (let x = 0; x < block.width; x++) {
      board.value[block.y + y][block.x + x] = 0;
    }
  }
  
  // 更新位置
  switch (direction) {
    case 'left': block.x--; break;
    case 'right': block.x++; break;
    case 'up': block.y--; break;
    case 'down': block.y++; break;
  }
  
  // 更新到棋盘
  updateBoard();
}

// 检查是否胜利
function checkVictory() {
  const caoBlock = blocks.value.find(block => block.type === '曹操');
  
  if (!caoBlock) return false;
  
  // 检查曹操是否到达出口位置
  return caoBlock.x <= exitPos.value[1] && 
         caoBlock.x + caoBlock.width > exitPos.value[1] && 
         caoBlock.y <= exitPos.value[0] && 
         caoBlock.y + caoBlock.height > exitPos.value[0];
}

// 重置关卡
function resetLevel() {
  loadLevel();
}

// 进入下一关
function nextLevel() {
  currentLevel.value++;
  loadLevel();
  closeVictoryModal();
}

// 关闭胜利弹窗
function closeVictoryModal() {
  isVictory.value = false;
}
</script>

<style scoped>
.huarongdao-game-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  font-family: 'Arial', sans-serif;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: 100vh;
}

.game-header {
  text-align: center;
  margin-bottom: 20px;
}

.game-header h1 {
  color: #333;
  font-size: 2.5rem;
  margin-bottom: 10px;
}

.game-info {
  display: flex;
  justify-content: center;
  gap: 30px;
  font-size: 1.2rem;
}

.info-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.info-label {
  color: #666;
  font-size: 0.9rem;
  margin-bottom: 5px;
}

.info-value {
  color: #333;
  font-weight: bold;
  font-size: 1.3rem;
}

.game-area {
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
}

.game-board {
  position: relative;
  background: #f0d9b5;
  border: 3px solid #8b4513;
  cursor: pointer;
}

.grid-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.grid-row {
  display: flex;
}

.grid-cell {
  width: 100%;
  height: 100%;
  border: 1px solid rgba(139, 69, 19, 0.3);
}

.blocks-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.game-block {
  position: absolute;
  border: 2px solid rgba(0, 0, 0, 0.2);
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: grab;
  transition: transform 0.1s ease;
  user-select: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.game-block:active {
  cursor: grabbing;
}

.game-block.dragging {
  opacity: 0.8;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.3);
}

.block-label {
  color: white;
  font-weight: bold;
  font-size: 1rem;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.3);
}

.game-controls {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
}

.control-button {
  padding: 10px 20px;
  font-size: 1rem;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  background-color: #3498db;
  color: white;
  transition: background-color 0.3s ease;
}

.control-button:hover {
  background-color: #2980b9;
}

.reset-button {
  background-color: #e74c3c;
}

.reset-button:hover {
  background-color: #c0392b;
}

.help-button {
  background-color: #95a5a6;
}

.help-button:hover {
  background-color: #7f8c8d;
}

.next-level-button {
  background-color: #2ecc71;
}

.next-level-button:hover {
  background-color: #27ae60;
}

.level-select {
  padding: 10px;
  font-size: 1rem;
  border: 1px solid #ddd;
  border-radius: 5px;
  background-color: white;
}

.game-help {
  background-color: white;
  padding: 15px 25px;
  border-radius: 5px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  max-width: 500px;
  text-align: left;
}

.game-help p {
  margin: 8px 0;
  color: #333;
}

.victory-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.victory-modal {
  background-color: white;
  padding: 30px;
  border-radius: 10px;
  text-align: center;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
  max-width: 400px;
  width: 90%;
}

.victory-modal h2 {
  color: #2ecc71;
  font-size: 2rem;
  margin-bottom: 10px;
}

.victory-modal p {
  color: #333;
  font-size: 1.1rem;
  margin: 10px 0;
}

.victory-buttons {
  display: flex;
  gap: 15px;
  justify-content: center;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .game-header h1 {
    font-size: 2rem;
  }
  
  .game-info {
    flex-direction: column;
    gap: 10px;
  }
  
  .game-controls {
    flex-wrap: wrap;
    justify-content: center;
  }
  
  .game-board {
    transform: scale(0.75);
    transform-origin: center;
  }
}
</style>